﻿using System;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json;

namespace FollowMe.GCM
{
    public static class PushNotification<T> where T : class
    {

        public static GCMResponse POST(GCMMessage<T> message, string apiKey)
        {
           //Create request:
            //HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.googleapis.com/gcm/send");
            //Request.Method = "POST";
            //Request.KeepAlive = false;
            //Request.ContentType = "application/json";
            //Request.Headers.Add(string.Format("Authorization: key={0}", apiKey));

           
            //MemoryStream stream1 = new MemoryStream();
            //DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(GCMMessage<T>));
            //ser.WriteObject(stream1, message);
            //stream1.Position = 0;
            //StreamReader sr = new StreamReader(stream1);
            //string jsonPostObject = sr.ReadToEnd();
           

            //add the message
            //Byte[] byteArray = ASCIIEncoding.UTF8.GetBytes(jsonPostObject);
            //Stream dataStream = Request.GetRequestStream();
            //dataStream.Write(byteArray, 0, byteArray.Length);
            //dataStream.Close();

            

            //the above commented code is an old way of doing the below.  I left it in in case this breaks:
            //serialize the object
            string jsonPostObject = JsonConvert.SerializeObject(message);

            //create a client
            HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            StringContent content = new StringContent(jsonPostObject, Encoding.UTF8, "application/json");
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", "=" + apiKey);

            //Send
            try
            {
                /**
                 * 200=sucess
                 *      multicast_id = id of multicast message
                 *      success = # w/o error
                 *      failure = # messages not processed
                 *      canonical_ids = https://developer.android.com/google/gcm/adv.html#canonical
                 *      results = array of info origonal message, any errors
                 * 400=could not be parsed
                 * 401=error auth
                 * 5xx=internal server error
                 **/

                HttpResponseMessage Response = httpClient.PostAsync("http://android.googleapis.com/gcm/send", content).Result;

               // WebResponse Response = Request.GetResponseAsync().Result; //old way

                HttpStatusCode ResponseCode = Response.StatusCode;

                GCMResponse response = null;

                switch(ResponseCode){
                    case(HttpStatusCode.BadRequest)://400
                        return new GCMResponse
                        {
                            success = false,
                            failure = 400
                        };
                    case(HttpStatusCode.Unauthorized)://401
                        return new GCMResponse
                        {
                            success = false,
                            failure = 401
                        };
                    case(HttpStatusCode.OK): //200
                        string responseLine = Response.Content.ReadAsStringAsync().Result;
                        if (responseLine != null)
                        {
                            response =  JsonConvert.DeserializeObject<GCMResponse>(responseLine);
                        }
                        break;
                }
                return response;
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            return new GCMResponse
            {
                success = false,
                failure = 500
            };
        }
    }
}